from django import forms
from .models import Notification
from django.utils import timezone

class NotificationForm(forms.ModelForm):
    """通知创建/编辑表单"""
    
    class Meta:
        model = Notification
        fields = ['title', 'content', 'target_roles', 'is_active', 'start_date', 'end_date', 'priority']
        widgets = {
            'title': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入通知标题'
            }),
            'content': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入通知内容...'
            }),
            'target_roles': forms.SelectMultiple(attrs={
                'class': 'form-control'
            }),
            'is_active': forms.CheckboxInput(attrs={
                'class': 'form-check-input'
            }),
            'start_date': forms.DateTimeInput(attrs={
                'class': 'form-control',
                'type': 'datetime-local'
            }),
            'end_date': forms.DateTimeInput(attrs={
                'class': 'form-control', 
                'type': 'datetime-local'
            }),
            'priority': forms.Select(attrs={
                'class': 'form-control'
            }),
        }
        labels = {
            'title': '通知标题',
            'content': '通知内容',
            'target_roles': '目标角色',
            'is_active': '是否激活',
            'start_date': '开始时间',
            'end_date': '结束时间',
            'priority': '优先级',
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # 设置目标角色的选择项
        self.fields['target_roles'].widget = forms.CheckboxSelectMultiple()
        self.fields['target_roles'].choices = Notification.ROLE_CHOICES
        
        # 设置必填字段
        self.fields['title'].required = True
        self.fields['content'].required = True
        self.fields['target_roles'].required = True
        self.fields['start_date'].required = True
        self.fields['end_date'].required = True
        
        # 设置时间字段的初始值
        if not self.instance.pk:
            now = timezone.now()
            self.fields['start_date'].initial = now
            self.fields['end_date'].initial = now.replace(hour=23, minute=59, second=59)

    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get('start_date')
        end_date = cleaned_data.get('end_date')
        
        # 验证时间范围
        if start_date and end_date and start_date >= end_date:
            raise forms.ValidationError("结束时间必须晚于开始时间")
        
        return cleaned_data

    def clean_target_roles(self):
        """验证目标角色字段"""
        target_roles = self.cleaned_data.get('target_roles', [])
        if not target_roles:
            raise forms.ValidationError("请至少选择一个目标角色")
        
        # 将列表转换为逗号分隔的字符串
        if isinstance(target_roles, list):
            return ','.join(target_roles)
        return target_roles
